package com.aftersale.platform.mapper;

import com.aftersale.platform.entity.Ticket;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface TicketMapper {

    @Results(id = "ticketResultMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "ticketType", column = "ticket_type"),
            @Result(property = "description", column = "description"),
            @Result(property = "status", column = "status"),
            @Result(property = "submitDate", column = "submit_date"),
            @Result(property = "progress", column = "progress"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "updatedAt", column = "updated_at"),
            @Result(property = "username", column = "user_id", javaType = String.class,
                    one = @One(select = "com.aftersale.platform.mapper.UserMapper.findUsernameById")) // 关联查询用户名
    })
    @Select("SELECT id, user_id, ticket_type, description, status, submit_date, progress, created_at, updated_at FROM tickets")
    List<Ticket> findAll();

    @ResultMap("ticketResultMap")
    @Select("SELECT id, user_id, ticket_type, description, status, submit_date, progress, created_at, updated_at FROM tickets WHERE id = #{id}")
    Ticket findById(Integer id);

    @ResultMap("ticketResultMap")
    @Select("SELECT id, user_id, ticket_type, description, status, submit_date, progress, created_at, updated_at FROM tickets WHERE user_id = #{userId}")
    List<Ticket> findByUserId(Integer userId);

    @Insert("INSERT INTO tickets (user_id, ticket_type, description, status, submit_date, progress) " +
            "VALUES (#{userId}, #{ticketType}, #{description}, #{status}, #{submitDate}, #{progress})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void save(Ticket ticket);

    @Update("UPDATE tickets SET ticket_type = #{ticketType}, description = #{description}, status = #{status}, " +
            "submit_date = #{submitDate}, progress = #{progress}, updated_at = CURRENT_TIMESTAMP WHERE id = #{id}")
    void update(Ticket ticket);

    @Delete("DELETE FROM tickets WHERE id = #{id}")
    void delete(Integer id);
}